<template lang="html">
  <div class="address-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size:16px">收货地址</span>
      </div>
      <div class="setup-address">
        <div class="add-address">
          <el-button  class="add-address-button" @click="handleShowDialogAddress()" plain>新增收货地址</el-button>
          <span class="add-address-span">您已创建{{addressList.length}}个收货地址，最多可创建20个</span>
        </div>
        <div class="address-list">
          <div class="address-item" v-for="(item,index) in addressList" :key="index" v-if="item.isDeleted==0">
            <div class="address-item-title">
              <strong >{{item.consignee}}</strong>
              <span class="default-address" v-if="item.isDefault==1">默认地址</span>
            </div>
            <i class="el-icon-close" @click='handleDel(index)'/>
            <div class="address-item-form">
              <div class="info-group">
                <div class="info-left">
                  收货人
                  <i></i>
                </div>
                <div class="" style="width:7px;float:left;margin-left: -2px;margin-right: 8px;" >
                  ：
                </div>
                <div class="info-right">
                  {{item.consignee}}
                </div>
              </div>
              <div class="info-group">
                <div class="info-left">
                  手机
                  <i></i>
                </div>
                <div class="" style="width:7px;float:left;margin-left: -2px;margin-right: 8px;" >
                  ：
                </div>
                <div class="info-right">
                  {{item.phone}}
                </div>
              </div>
              <div class="info-group">
                <div class="info-left">
                  所在地区
                  <i></i>
                </div>
                <div class="" style="width:7px;float:left;margin-left: -2px;margin-right: 8px;" >
                  ：
                </div>
                <div class="info-right">
                  {{ item.provinceName }} {{ item.cityName }} {{ item.districtName }}
                </div>
              </div>
              <div class="info-group">
                <div class="info-left">
                  地址
                  <i></i>
                </div>
                <div class="" style="width:7px;float:left;margin-left: -2px;margin-right: 8px;" >
                  ：
                </div>
                <div class="info-right">
                  {{ item.address }}
                </div>
              </div>
              <div class="edit-address">
                <div class="edit-default" v-if="item.isDefault==0" @click="setDefaultAddress(item.id,item.userId)">
                  设为默认地址
                </div>
                <div class="edit-info" @click="handleShowDialogAddress(index)">
                  编辑
                </div>
              </div>
            </div>
          </div>

        </div>
        <div class="address-nodata" v-if="!addressList||addressList.length==0">
          <img src="@/assets/images/member/notorder.png" />
          <p>暂时还没添加任何地址哦~</p>
        </div>
      </div>
    </el-card>




    <div class="">
      <!--新增地址-->
      <el-dialog :title="title" :visible.sync="dialogAddress" custom-class="form-dialog-address" width="600px" @close="dialogAddressClose()">
        <el-form :model="formAddress" :rules="rules" ref="formAddress" label-width="130px">
          <el-form-item label="姓名" prop="consignee">
            <el-input v-model="formAddress.consignee" placeholder="请输入收货人姓名" maxlength="25"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="formAddress.phone" placeholder="请输入收货人手机号码" maxlength="11"></el-input>
          </el-form-item>
          <el-form-item label="所在地区">
            <SelectArea ref="children" class="no-ver" @changeArea="changeArea" :area="area" />
            <!-- <el-input v-model="formAddress.districtId" autocomplete="off"></el-input> -->
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="formAddress.address" placeholder="如道路、门牌号、楼栋号" maxlength="50"></el-input>
          </el-form-item>
          <el-checkbox v-model="isDefault" class="checkbox">设为默认地址</el-checkbox>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddress = false">取 消</el-button>
          <el-button type="primary" @click="handleSave()">保 存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import SelectArea from '@/components/SelectArea'
import { getAddressList, addAddress, updateAddress,setDefaultAddress,deleteAddress } from '@/api/member'
export default {
  name: 'MemberAddress',
  components: {
    SelectArea
  },
  data() {
    const checkMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else {
        if(!/^1\d{10}$/.test(value)){
          callback(new Error('请输入11位手机号码'))
        }else{
          callback();
        }
      }
    }
    return {
      userInfo:this.getUserInfo(),
      addressList:[],
      form:{
        name: '',
      },
      title:'新增收货信息',
      area: null,
      bool:true,
      dialogAddress:false,
      editAddressInfo: '',
      isDefault:false,
      formAddress: {
        consignee: "",
        phone: "",
        address: "",
        zipCode: "1",
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        districtId: "",
        districtName: ""
      },
      rules: {
        consignee: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: checkMobile, trigger: 'blur' }
        ],
        // provinceId: [
        //   { required: true, message: '请选择所在地区', trigger: 'blur' }
        // ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
      },

    }
  },
  created() {
    this.getAddressList();
  },
  methods: {
    handleDel(index) {
         this.$confirm('是否删除该地址', '', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           center:true
         }).then(() =>{
           this.deleteAddress(index);
         })
  },

    //删除地址
    deleteAddress(index){
      deleteAddress({id:this.addressList[index].id}).then(res =>{
        if (res.code == 200) {
          this.$message.success('删除成功');
          this.getAddressList();
        }
      })
    },
    //设置默认地址
    setDefaultAddress(addressId,userId){
      setDefaultAddress({id:addressId,userId:userId}).then(res =>{
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.getAddressList();
        }
    })
  },
    //获得地址列表
    getAddressList(){
      getAddressList().then(res =>{
        if(res.code == 200){
          this.addressList = res.data;
        }
      })
    },
    //显示地址弹窗
    handleShowDialogAddress(index) {
      if(index!=undefined){
        this.title = '修改收货信息'
        this.editAddressInfo = this.addressList[index];
        this.isDefault = this.addressList[index].isDefault == 1 ?  true : false;
        for(let i in this.editAddressInfo){
          this.formAddress[i] = this.editAddressInfo[i]
        }
        let provinceId = this.editAddressInfo.provinceId
        let provinceName = this.editAddressInfo.provinceName
        let cityId = this.editAddressInfo.cityId
        let cityName = this.editAddressInfo.cityName
        let districtId = this.editAddressInfo.districtId
        let districtName = this.editAddressInfo.districtName
        this.$nextTick(() => {
          this.area = [
            {
              [provinceId] : provinceName
            },
            {
              [cityId] : cityName
            },
            {
              [districtId] : districtName
            }
          ]
        });
        this.dialogAddress = true;
      }else{
        this.title = '新增收货信息'
        if (this.getAddressList.length >= 20) {
          this.$message.warning("最多创建20个收货地址");
          return;
        }else {
          this.dialogAddress = true;
        }
      }

    },
    // 处理关闭弹窗
    dialogAddressClose(){
      this.isDefault = false;
      this.formAddress.consignee = ""
      this.formAddress.phone = ""
      this.formAddress.address = ""
      this.formAddress.zipCode = ""

      this.$nextTick(() => {
        this.area = []
      });

    },
    // 处理保存
    handleSave(){

      this.$refs.formAddress.validate((valid) => {
        if (valid) {
          if(this.formAddress.provinceId == ''){
            this.$message({
              type: 'error',
              message: '请选择所在地区'
            });
            return;
          }
          if(this.title == '新增收货信息'){
            this.addAddress()
          }else{
            this.updateAddress()
          }
        } else {
          return false;
        }
      });
    },
    //保存地址
    addAddress() {

      const params = this.formAddress;
      params.isDefault = this.isDefault ? 1 : 0;
      addAddress(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.getAddressList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
        this.dialogAddress = false;
      })
    },
    //修改地址
    updateAddress() {
      const params = this.formAddress;
      params.isDefault = this.isDefault ? 1 : 0;
      params.id = this.editAddressInfo.id;
      updateAddress(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.getAddressList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
        this.dialogAddress = false;
      })
    },

    //获取地区
    changeArea(val) {
      let result = []
      if(val.length){
        val.forEach((item, i) => {
          for(let i in item){
            result.push({
              key: i,
              value: item[i]
            })
          }
        })
      };
      this.formAddress.provinceId = result[0].key,
      this.formAddress.provinceName = result[0].value,
      this.formAddress.cityId = result[1].key,
      this.formAddress.cityName = result[1].value,
      this.formAddress.districtId = result[2].key,
      this.formAddress.districtName = result[2].value
    },

  }

}


</script>

<style lang="scss">
.default-address{
  display: inline-block;
  vertical-align: top;
  width: 60px;
  text-align: center;
  height: 20px;
  line-height: 20px;
  color: #fff;
  background-color:#F3B851;
  font-size: 12px;
  margin-left: 10px;
}
.address-container{
  margin-left: 200px;
  margin-top: 20px;
  margin-bottom: 20px;
}
.edit-address{
  float: right;
  margin-top: -35px;
  font-size: 14px;
  color: #255B8B;
  .edit-default{
    float: left;
    margin-right: 57px;
    cursor: pointer;
  }
  .edit-info{
    float: right;
    margin-right: 30px;
    cursor: pointer;
  }
}
.address-item .el-icon-close{
  float: right;
  font-size: 16px;
  margin-top: -21px;
  margin-right: 30px;
  cursor: pointer;
}
.address-item-form{
  .info-group{
    width: 100%;
    margin: 20px 30px;
    font-size: 12px;
    .info-left{
      float: left;
      width: 48px;
      text-align: justify;

      i{
        display:inline-block;
        padding-left: 100%;
      }
    }
    .info-right{

    }
  }

}

.add-address{
  height: 84px;
  width: 100%;
}

.address-item{
  width:920px;
  height:185px;
  background:#F9F9F9;
  border:1px solid #DDDDDD;
  margin-left: 40px;
  margin-bottom: 20px;
  .address-item-title{
    margin: 19px 0 4px 30px;
    strong{
      font-size: 16px;
      color: #333333;
      font-family: PingFang-SC-Bold;
    }
  }

}
.add-address{
  .el-button.is-plain:focus,.el-button.is-plain:hover{
    background-color: #D3DEE8;
    border: 1px solid #255B8A;
  }
  button{
    height: 34px;
    margin: 30px auto 20px 40px;
    width: 100px;
    padding: 0;
    background-color: #D3DEE8;
    border: 1px solid #255B8A;
    span{
      color: #255B8A;
      font-size: 12px;
    }
  }
  .add-address-span{
    margin-left: 10px;
    margin-top: 41px;
    font-size: 12px;
    color: #888888;
  }

}

.form-dialog-address{
  .el-form-item__content{
    margin-right: 21px;
  }
  .checkbox{
    margin-left: 130px;
  }
  .area-select-wrap .area-select{
    margin-left: 0;
    margin-right: 2px;
    &:last-child{
      margin-right: 0;
    }
  }
}
.address-nodata{
  text-align: center;
  padding: 30px 0;
}
</style>
